package com.peanut.baby.mvp.calendar;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.peanut.baby.AppConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.db.DBManager;
import com.peanut.baby.model.CalendarRecord;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.calendar.decorators.IconDecorator;
import com.peanut.baby.mvp.calendar.decorators.TextColorDecorator;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by anonymouslystudio on 2017/7/12.
 */

public class CalendarActivity extends BaseMvpActivity
        implements TitleLayout.OnTitleClickListener,
        OnDateSelectedListener, View.OnClickListener,CalendarContract.View {
    private static final String TAG = CalendarActivity.class.getSimpleName();
    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.calendar_view)
    MaterialCalendarView calendarView;
    @BindView(R.id.tongfang)
    TextView tongfang;
    @BindView(R.id.tiwen)
    TextView tiwen;
    @BindView(R.id.yesuan)
    TextView yesuan;
    @BindView(R.id.baidai)
    TextView baidai;
    @BindView(R.id.tongfang_more)
    ImageView tongfangMore;
    @BindView(R.id.tiwen_more)
    ImageView tiwenMore;
    @BindView(R.id.yesuan_more)
    ImageView yesuanMore;
    @BindView(R.id.baidai_more)
    ImageView baidaiMore;
    @BindView(R.id.dayima)
    TextView dayima;
    @BindView(R.id.dayima_more)
    ImageView dayimaMore;
    @BindView(R.id.content_container)
    LinearLayout contentContainer;
    @BindView(R.id.tips_container)
    LinearLayout tipsContainer;
    @BindView(R.id.tips_back)
    TextView tipsBack;

    private CalendarPresenter presenter;

    public static void start(Context ctx) {
        ctx.startActivity(new Intent(ctx, CalendarActivity.class));
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar);
        ButterKnife.bind(this);
        presenter = new CalendarPresenter(this,this);
        initView();

        showProgressDialog("请稍候...",false);
        presenter.getData();
    }

    private void initView() {
        title.setTitle("记录");
        title.setOnTitleClickedListener(this);
        dayima.setOnClickListener(this);
        tongfang.setOnClickListener(this);
        tiwen.setOnClickListener(this);
        yesuan.setOnClickListener(this);
        baidai.setOnClickListener(this);
        tongfangMore.setOnClickListener(this);
        tiwenMore.setOnClickListener(this);
        yesuanMore.setOnClickListener(this);
        baidaiMore.setOnClickListener(this);
        dayimaMore.setOnClickListener(this);

        tipsBack.setOnClickListener(this);


        calendarView.setOnDateChangedListener(this);

    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {

    }

    @Override
    public void onTitleClicked() {

    }

    /**
     * 展示今天的数据
     */
    private void displayDataOfToday(){
        calendarView.setSelectedDate(CalendarDay.today());
        resetAndDisplayDateOfDate(calendarView.getSelectedDate().getDate());

    }

    @Override
    public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
        Log.d(TAG, "onDateSelected " + selected + " " + date.toString());
        if (date.isAfter(CalendarDay.today())) {
            tipsContainer.setVisibility(View.VISIBLE);
            contentContainer.setVisibility(View.GONE);
        } else {
            tipsContainer.setVisibility(View.GONE);
            contentContainer.setVisibility(View.VISIBLE);

            resetAndDisplayDateOfDate(date.getDate());
        }


    }

    /**
     * 重置所有数据后展示某一天的数据
     * @param date
     */
    private void resetAndDisplayDateOfDate(Date date){
        Log.d(TAG,"resetAndDisplayDateOfDate "+CalUtil.dateToString(date));
        resetAllValuesWhenDateChanged();
        displayDataOfDate(date);
    }

    /**
     * 重置所有数据
     */
    private void resetAllValuesWhenDateChanged(){
        dayima.setText("");
        dayimaMore.setVisibility(View.VISIBLE);

        tongfang.setText("");
        tongfangMore.setVisibility(View.VISIBLE);

        tiwen.setText("");
        tiwenMore.setVisibility(View.VISIBLE);

        yesuan.setText("");
        yesuanMore.setVisibility(View.VISIBLE);

        baidai.setText("");
        baidaiMore.setVisibility(View.VISIBLE);
    }

    /**
     * 展示某一天的数据
     * @param date
     */
    private void displayDataOfDate(Date date){
        CalendarRecord record = presenter.getRecordFromDB(Integer.parseInt(InitManager.getInstance().getUserId()),CalUtil.dateToString(date));
        if(record != null){
            dayima.setText(record.dayima);
            dayimaMore.setVisibility(!StringUtil.isNullOrEmpty(record.dayima)?View.GONE:View.VISIBLE);

            tongfang.setText(record.tongfang);
            tongfangMore.setVisibility(!StringUtil.isNullOrEmpty(record.tongfang)?View.GONE:View.VISIBLE);

            tiwen.setText(record.tiwen);
            tiwenMore.setVisibility(!StringUtil.isNullOrEmpty(record.tiwen)?View.GONE:View.VISIBLE);

            yesuan.setText(record.yesuan);
            yesuanMore.setVisibility(!StringUtil.isNullOrEmpty(record.yesuan)?View.GONE:View.VISIBLE);

            baidai.setText(record.baidai);
            baidaiMore.setVisibility(!StringUtil.isNullOrEmpty(record.baidai)?View.GONE:View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case AppConfig.RequestResult.REQUEST_CODE_BAIDAI:
                String result = data.getStringExtra(Intent.EXTRA_RETURN_RESULT);
                if(result.equals("无")){
                    baidai.setText("");
                    baidaiMore.setVisibility(View.VISIBLE);
                }else{
                    baidai.setText(result);
                    baidaiMore.setVisibility(View.GONE);
                }

                submitWhenDataChanged();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tongfang:
            case R.id.tongfang_more:
                String t = tongfang.getText().toString();
                new BaseDialog().showSinglePickerDialog(CalendarActivity.this, "同房",
                        getResources().getStringArray(R.array.tongfang_values), t, new BaseDialog.OnPickerListener() {
                            @Override
                            public void onPickered(String value) {
                                if (StringUtil.isNullOrEmpty(value)) {
                                    tongfang.setText("");
                                    tongfangMore.setVisibility(View.VISIBLE);
                                } else {
                                    tongfang.setText(value);
                                    tongfangMore.setVisibility(View.GONE);
                                }
                                submitWhenDataChanged();
                            }
                        });
                break;
            case R.id.tiwen:
            case R.id.tiwen_more:
                String[] spilt = spiltCurrentTiwen(tiwen.getText().toString());
                Log.d(TAG, "spilt->" + (spilt == null ? "null" : "size: " + spilt.length));
                new BaseDialog().showTiWenPickerDialog(CalendarActivity.this,
                        getResources().getStringArray(R.array.tiwen_values1),
                        getTiwenValue2(),
                        spilt == null ? "" : spilt[0],
                        spilt == null ? "" : "." + spilt[1],
                        new BaseDialog.onTiWenPickerListener() {

                            @Override
                            public void onPickered(String value1, String value2) {
                                if (StringUtil.isNullOrEmpty(value1) || StringUtil.isNullOrEmpty(value2)) {
                                    tiwen.setText("");
                                    tiwenMore.setVisibility(View.VISIBLE);
                                } else {
                                    tiwen.setText(value1 + "" + value2);
                                    tiwenMore.setVisibility(View.GONE);
                                }
                                submitWhenDataChanged();
                            }
                        });
                break;
            case R.id.yesuan:
            case R.id.yesuan_more:
                String y = yesuan.getText().toString();
                new BaseDialog().showSinglePickerDialog(CalendarActivity.this, "叶酸",
                        getResources().getStringArray(R.array.yesuan_values), y, new BaseDialog.OnPickerListener() {
                            @Override
                            public void onPickered(String value) {
                                if (StringUtil.isNullOrEmpty(value)) {
                                    yesuan.setText("");
                                    yesuanMore.setVisibility(View.VISIBLE);
                                } else {
                                    yesuan.setText(value);
                                    yesuanMore.setVisibility(View.GONE);
                                }
                                submitWhenDataChanged();
                            }
                        });
                break;
            case R.id.baidai:
            case R.id.baidai_more:
                BaidaiOptionsActivity
                        .startForResult(this, baidai.getText().toString());
                break;
            case R.id.dayima:
            case R.id.dayima_more:
                String d = dayima.getText().toString();
                new BaseDialog().showSinglePickerDialog(CalendarActivity.this, "大姨妈",
                        getResources().getStringArray(R.array.dayima_values), d, new BaseDialog.OnPickerListener() {
                            @Override
                            public void onPickered(String value) {
                                Log.d(TAG,"on dayima picked "+value);
                                if (StringUtil.isNullOrEmpty(value)) {
                                    dayima.setText("");
                                    dayimaMore.setVisibility(View.VISIBLE);
                                } else {
                                    dayima.setText(value);
                                    dayimaMore.setVisibility(View.GONE);

                                }
                                submitWhenDataChanged();
//                                onMenseChanged(dayima.getText().toString());
                            }
                        });
                break;
            case R.id.tips_back:
                Log.d(TAG,"b");
                calendarView.setSelectedDate(CalendarDay.today());
                calendarView.setCurrentDate(CalendarDay.today(),true);
                onDateSelected(calendarView,CalendarDay.today(),true);
                break;
        }
    }

    private String[] getTiwenValue2() {
        String[] result = new String[100];
        for (int i = 0; i < 100; i++) {
            if (i < 10) {
                result[i] = ".0" + i + "°C";
            } else {
                result[i] = "." + i + "°C";
            }
        }
        return result;
    }

    private String[] spiltCurrentTiwen(String current) {
        if (current.contains("°C")) {
            return current.split("\\.");
        }
        return null;
    }

    /**
     * 大姨妈的值改变了，重新计算排卵日和易孕期等
     *
     * @param newValue
     */
//    private void onMenseChanged(String newValue) {
//
//        if (newValue.equals(AppConfig.StringConstants.MENSE_COME)) {
//            setMenseStartDate();
//        } else if (newValue.equals(AppConfig.StringConstants.MENSE_GO)) {
//            //走了
//            setMenseEndDate();
//        } else {
//            //清除置空
//
//        }
//    }

    /**
     *  设置月经开始日期
     */
//    private void setMenseStartDate() {
//        final Date selectedDate = calendarView.getSelectedDate().getDate();
//        //先检查日期，检查前后几天是否有标记大姨妈来了或者走了
//        List<CalendarRecord> records = DBManager.getInstance().getCalendarRecordWithMense(Integer.parseInt(InitManager.getInstance().getUserId()));
//        if(records != null && !records.isEmpty()){
//            //先把最近的大姨妈来了走了都找出来
//            final CalendarRecord recentStart = MenseUtil.getRecentMenseRecord(selectedDate,
//                    records,
//                    AppConfig.StringConstants.MENSE_COME);
//            final CalendarRecord recentGo = MenseUtil.getRecentMenseRecord(selectedDate,
//                    records,
//                    AppConfig.StringConstants.MENSE_GO);
//            if(recentStart == null){
//                //最近的标记来了没有记录
//                if(recentGo == null){
//                    Log.d(TAG,"没有标记来了和走了");
//                    //最近的走了没有记录，既没有标记过来了也没有标记过走了，直接按首次标记处理
//                    doChangeMenseStartDate(selectedDate,null);
//                    submitWhenDataChanged();
//                }else{
//                    Log.d(TAG,"没有标记来了但标记走了");
//                    //最近标记过走了，计算时间差，时间差超过特定天数 不处理
//                    int diffDays = CalUtil.daysBetween(recentGo.date,CalUtil.dateToString(selectedDate));
//                    Log.d(TAG,"日期差： "+diffDays);
//                    if(diffDays == 0){
//                        //同一天标记过走了
//                        Log.d(TAG,"同一天标记过走了...、、TODO 修改这一天为'来了'");
//                        doChangeMenseStartDate(selectedDate,null);
//                        submitWhenDataChanged();
//                    }else{
//                       if(diffDays < 0){
//                           Log.d(TAG,"前边的日期中有标过走了，直接标记选中为来了");
//                           doChangeMenseStartDate(selectedDate,null);
//                           submitWhenDataChanged();
//                        }else{
//                           Log.d(TAG,"后边的日期中有标过走了，但是没标记过来了");
//                           //TODO 加日期天数判断，大于多少天的忽略以前走了的记录
//                           doChangeMenseStartDate(selectedDate,CalUtil.stringToDate(recentGo.date));
//                       }
//
//                    }
//                }
//            }else{
//                if(recentGo == null){
//                    Log.d(TAG,"标记了来了但是没标记走了");
//                    Log.d(TAG,"计算日期差 如果日期差在10天以内，则询问是否更换，否则直接标记");
//                    int diffDays = CalUtil.daysBetween(CalUtil.dateToString(selectedDate),recentStart.date);
//                    if(Math.abs(diffDays) <= 10){
//                        //同一天标记过走了
//                        new BaseDialog().showConfirmCancelAlert(CalendarActivity.this, "是否修改当前日期为大姨妈'来了'？", "确定", "取消", new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                doChangeMenseStartDate(selectedDate,null);
//                                submitWhenDataChanged();
//                            }
//                        }, new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                dayima.setText("");
//                                dayimaMore.setVisibility(View.VISIBLE);
//                                submitWhenDataChanged();
//                            }
//                        });
//
//
//                    }else{
//                        Log.d(TAG,"以前标记的'来了'和当前选中日期相距大于10天，直接标记当前为开始即可");
//                        doChangeMenseStartDate(selectedDate,null);
//                        submitWhenDataChanged();
//                    }
//                }else{
//                    Log.d(TAG,"来了和走了都有标记过");
//                    //TODO
//
//
//                }
//            }
//
//        }else{
//            Log.d(TAG,"没有大姨妈来了或者走了的记录");
//            doChangeMenseStartDate(selectedDate,null);
//            submitWhenDataChanged();
//        }
//    }

    /**
     * 执行大姨妈来了的操作
     * @param endDate  结束日期 没有设置为null null时按默认经期天数算
     */
    private void doChangeMenseStartDate(Date startDate,Date endDate){
        calendarView.removeDecorators();
        Log.d(TAG, "doChangeMenseStartDate " + CalUtil.dateToString(startDate));
        reCalculatePeriods(startDate,endDate);
    }

    /**
     *  设置月经结束时间
     */
//    private void setMenseEndDate(){
//        final Date selectedDate = calendarView.getSelectedDate().getDate();
//        //先检查日期，检查前后几天是否有标记大姨妈来了或者走了
//        List<CalendarRecord> records = DBManager.getInstance().getCalendarRecordWithMense(Integer.parseInt(InitManager.getInstance().getUserId()));
//        if(records != null && !records.isEmpty()) {
//            //先把最近的大姨妈来了走了都找出来
//            final CalendarRecord recentStart = MenseUtil.getRecentMenseRecord(selectedDate,
//                    records,
//                    AppConfig.StringConstants.MENSE_COME);
//            final CalendarRecord recentGo = MenseUtil.getRecentMenseRecord(selectedDate,
//                    records,
//                    AppConfig.StringConstants.MENSE_GO);
//
//            if(recentStart == null){
//                //最近的标记来了没有记录
//                Log.d(TAG,"没标记过开始 什么都不做");Log.d(TAG,"以前没标记过开始或结束，什么都不做");
//                new BaseDialog().showConfirmAlert(CalendarActivity.this, "请先标记大姨妈来的日期", "确定", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        dayima.setText("");
//                        dayimaMore.setVisibility(View.VISIBLE);
//                    }
//                });
//
//            }else{
//                if(recentGo == null){
//                    Log.d(TAG,"标记了来了但是没标记走了");
//                    Log.d(TAG,"计算日期差 如果日期差在10天以内，则询问是否更换，否则直接标记");
//                    int diffDays = CalUtil.daysBetween(CalUtil.dateToString(selectedDate),recentStart.date);
//                    if(Math.abs(diffDays) <= 10){
//                        //TODO
////                        doChangeMenseStartDate(selectedDate,null);
//                    }else{
//                        Log.d(TAG,"以前标记的'来了'和当前选中日期相距大于10天，则提示是否标记当前为结束");
//
//                        if(diffDays > 0){
//
//                        }else{
//                            new BaseDialog().showConfirmCancelAlert(CalendarActivity.this,
//                                    "当前标记的开始时间距选中时间大于10天，是否继续标记？",
//                                    "确定",
//                                    "取消", new View.OnClickListener() {
//                                        @Override
//                                        public void onClick(View v) {
//                                            doChangeMenseStartDate(CalUtil.stringToDate(recentStart.date),selectedDate);
//                                            submitWhenDataChanged();
//                                        }
//                                    }, new View.OnClickListener() {
//                                        @Override
//                                        public void onClick(View v) {
//                                            dayima.setText("");
//                                            dayimaMore.setVisibility(View.VISIBLE);
//                                        }
//                                    });
//                        }
//
//                    }
//                }else{
//                    Log.d(TAG,"来了和走了都有标记过");
//
//                }
//            }
//        }else{
//            //do nothing..
//            Log.d(TAG,"以前没标记过开始或结束，什么都不做");
//            new BaseDialog().showConfirmAlert(CalendarActivity.this, "请先标记大姨妈来的日期", "确定", new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    dayima.setText("");
//                    dayimaMore.setVisibility(View.VISIBLE);
//                }
//            });
//        }
//    }

    /**
     * 依据大姨妈开始时间重新计算排卵日、易孕期、月经期等
     * @param menseStartDate
     */
    private void reCalculatePeriods(Date menseStartDate,Date menseEndDate) {
        Date[] period = CalUtil.getPregnantPeriodWithYuejingStartDate(menseStartDate);
        Date pailuan = CalUtil.getPailuanDay(menseStartDate);

        Date[] yuejingPeriod = null;
        if(menseEndDate != null){
            yuejingPeriod = new Date[2];
            yuejingPeriod[0] = menseStartDate;
            yuejingPeriod[1] = menseEndDate;
        }else{
            //根据默认月经天数计算
            yuejingPeriod = CalUtil.getYuejingPeriodWithYuejingStartDate(menseStartDate);
        }


        displayMensePeriod(yuejingPeriod);
        displayPailuanDate(pailuan);
        displayPregnantablePeriod(period);
    }

    /**
     * 画经期
     * @param period
     */
    private void displayMensePeriod(Date[] period){
        Log.d(TAG,"displayMensePeriod: "+(period == null? "period not define":CalUtil.dateToString(period[0])+"-"+CalUtil.dateToString(period[1])));
        Calendar calendar = Calendar.getInstance();
        //画月经预测期
        if (period != null) {
            ArrayList<CalendarDay> periodArray = new ArrayList<>();
            int d = CalendarCache.getYuejingColor();

            calendar.setTime(period[0]);
            int days = CalUtil.daysBetweenPlusOne(period[0], period[1]);
            for (int i = 0; i < days; i++) {
                CalendarDay day = CalendarDay.from(calendar);
                periodArray.add(day);
                calendar.add(Calendar.DATE, 1);
            }
            calendarView.addDecorator(new TextColorDecorator(d, periodArray));
        }

    }

    /**
     * 画排卵日
     * @param pailuanDate
     */
    private void displayPailuanDate(Date pailuanDate){
        Log.d(TAG,"displayPailuanDate: "+(pailuanDate == null? "date not define":CalUtil.dateToString(pailuanDate)));
        if (pailuanDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(pailuanDate);
            CalendarDay pailuanDay = CalendarDay.from(calendar);
            ArrayList<CalendarDay> pailuanArray = new ArrayList<>();
            pailuanArray.add(pailuanDay);

            Bitmap bit = CalendarCache.getPailuanBitmap();

            calendarView.addDecorator(new IconDecorator(bit, pailuanArray));

        }
    }

    /**
     * 画易孕期
     * @param period
     */
    private void displayPregnantablePeriod(Date[] period){
        Log.d(TAG,"displayPregnantablePeriod: "+(period == null? "period not define":CalUtil.dateToString(period[0])+"-"+CalUtil.dateToString(period[1])));
        if (period != null) {
            Calendar calendar = Calendar.getInstance();
            //画易孕日
            ArrayList<CalendarDay> periodArray = new ArrayList<>();
            int d = CalendarCache.getYiyunColor();

            calendar.setTime(period[0]);
            int days = CalUtil.daysBetweenPlusOne(period[0], period[1]);
            for (int i = 0; i < days; i++) {
                CalendarDay day = CalendarDay.from(calendar);
                periodArray.add(day);
                calendar.add(Calendar.DATE, 1);
            }
            calendarView.addDecorator(new TextColorDecorator(d, periodArray));
        }
    }

    @Override
    public void onDataGet(List<CalendarRecord> records) {
        dismissProgressDialog();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                displayDataOfToday();
                reDecoratCalendarWhenDataChanged();
            }
        });
    }

    @Override
    public void onDataGetFailed(String reason) {
        dismissProgressDialog();
    }

    @Override
    public void onSubmitDataSuccess(CalendarRecord record) {
        reDecoratCalendarWhenDataChanged();
    }

    @Override
    public void onSubmitDataFailed(String reason) {
        reDecoratCalendarWhenDataChanged();
    }

    /**
     * 数据改变后重新加载数据
     */
    private void reDecoratCalendarWhenDataChanged(){
        calendarView.removeDecorators();
        List<CalendarRecord> records = DBManager.getInstance().getAllCalendarRecord(Integer.parseInt(InitManager.getInstance().getUserId()));
        if(records == null || records.isEmpty()){
            return;
        }
        Collections.sort(records);

        ArrayList<CalendarDay> menseStartArray = new ArrayList<>();
        ArrayList<CalendarDay> menseEndArray = new ArrayList<>();
        ArrayList<CalendarDay> recordArray = new ArrayList<>();

        //test
        for(int i=0;i<records.size();i++){
            final CalendarRecord record = records.get(i);
            if(!StringUtil.isNullOrEmpty(record.dayima)){
                if(record.dayima.equals(AppConfig.StringConstants.MENSE_COME)){
                    menseStartArray.add(CalendarDay.from(CalUtil.stringToDate(record.date)));
                    CalendarRecord goRecord = getRecentMenseGoRecord(i,records);

                    //判断如果没有月经走了 要计算一个默认值
                    if(goRecord == null){
                        Date[] period = CalUtil.getYuejingPeriodWithYuejingStartDate(record.date);
                        if(period != null){
                            menseEndArray.add(CalendarDay.from(period[1]));
                        }
                    }else{
                        menseEndArray.add(CalendarDay.from(CalUtil.stringToDate(goRecord.date)));
                    }
                    reCalculatePeriods(CalUtil.stringToDate(record.date),goRecord == null? null:CalUtil.stringToDate(goRecord.date));
                }else{
                    //大姨妈走了
                    menseEndArray.add(CalendarDay.from(CalUtil.stringToDate(record.date)));
                }
            }else{
                //有记录标示
                recordArray.add(CalendarDay.from(CalUtil.stringToDate(record.date)));
            }
        }

        calendarView.addDecorator(new IconDecorator(CalendarCache.getMenseStartBitmap(), menseStartArray));
        calendarView.addDecorator(new IconDecorator(CalendarCache.getMenseEndBitmap(), menseEndArray));
        calendarView.addDecorator(new IconDecorator(CalendarCache.getHasRecordBitmap(), recordArray));
    }

    /**
     *
     * @param index
     * @param source
     * @return
     */
    private CalendarRecord getRecentMenseGoRecord(int index,List<CalendarRecord> source){
        if(source == null || source.isEmpty()){
            return null;
        }

        if(index <0 || index >source.size()-1){
            return null;
        }
        for(int i = index+1;i<source.size();i++){
            final CalendarRecord record = source.get(i);
            if(!StringUtil.isNullOrEmpty(record.dayima)){
                if(record.dayima.equals(AppConfig.StringConstants.MENSE_COME)){
                    Log.i(TAG,"\t两个来了挨着 直接返回null"+i+" "+record.toString());
                    //两个来了挨着
                    return null;
                }
                if(record.dayima.equals(AppConfig.StringConstants.MENSE_GO)){
                    Log.i(TAG,"\t最近的选项"+i+" "+record.toString());
                    int daysDiff = CalUtil.daysBetween(record.date,source.get(index).date);
                    if(Math.abs(daysDiff) > 10){
                        return null;
                    }else{
                        return record;
                    }
                }

            }

        }
        return null;
    }



    private void submitWhenDataChanged(){
        Log.d(TAG,"submitWhenDataChanged "+(calendarView.getSelectedDate() == null? null: calendarView.getSelectedDate().toString()));
        if(calendarView.getSelectedDate() == null)
            return;
        String date = CalUtil.dateToString(calendarView.getSelectedDate().getDate());
        String logA = dayima.getText().toString().trim();
        String logB = tongfang.getText().toString().trim();
        String logC = tiwen.getText().toString().trim();
        String logD = yesuan.getText().toString().trim();
        String logE = baidai.getText().toString().trim();

        presenter.updateData(date,logA,logB,logC,logD,logE);

    }
}
